#include "tcpClient.h"

#include <iostream>
#include "sys/signal.h"
#include "sys/file.h"
#include "mqCommon.h"

static tcpClient service;
static int fd;
static mqd_t mq;

static void parentExit(int signum)
{
    // 忽略进入信号
    signal(SIGTERM, SIG_IGN);
    signal(SIGINT, SIG_IGN);

    // 向子进程发送信号
    kill(0, signum);

    // 释放资源
    service.close();

    // 解除文件锁
    flock(fd, LOCK_UN);
    close(fd);
    mq_close(mq);


    // 退出程序
    exit(0);
}


int main(int argc, char* argv[])
{
    // 忽略无关信号
    for(int i = 1; i < NSIG; i++)
    {
        signal(i, SIG_IGN);
    }
    // 注册退出信号处理函数
    signal(SIGTERM, parentExit);
    signal(SIGINT, parentExit);

    // 文件锁机制仅能运行一个进程
    fd = open("/tmp/tcpMain.lock", O_CREAT | O_RDWR, 0666);
    if(fd == -1) 
    {
        perror("open");
        return 1;
    }
    // 尝试加锁
    if(flock(fd, LOCK_EX | LOCK_NB) == -1) 
    {
        close(fd);
        std::cout << "the process already exists" << endl;
        return 1;
    }
    // 判断参数输入
    if(argc != 3)
    {
        std::cout << "please input <ip> <port>" << endl;
        return 1;
    }
    // 只读的方式打开消息队列
    struct mq_attr attr {};
    attr.mq_flags   = 0;
    attr.mq_maxmsg  = MQ_MAXMSG;
    attr.mq_msgsize = MQ_MSGSIZE;
    mq = mq_open(MQ_NAME, O_RDONLY, 0666, &attr);
    // 接收缓冲
    char buf[MQ_MSGSIZE];   
    unsigned int prio;
    ssize_t len;
    // App------------------------------------------------

    if(!service.connect(argv[1],atoi(argv[2])))
    {
        std::cout << "connect fail" << endl;
    }
    else
    {
        std::cout << "connect success,input ctrl+C close" << endl;
        while(true)
        {
            len = mq_receive(mq, buf, sizeof(buf), &prio);
            if (len == -1) 
            {              
                perror("mq_receive");
                break;
            }
            std::string data(buf, len);
            if(!service.send(data))
            {
                perror("send");
                break;
            }
        }
    }

    // ---------------------------------------------------

    // 解锁并退出
    flock(fd, LOCK_UN);
    close(fd);
    mq_close(mq);

    return 0;
}








